package com.gzhuxj201.interceptor;

import com.gzhuxj201.entity.Admin;
import com.gzhuxj201.entity.Student;
import com.gzhuxj201.entity.Teacher;
import com.gzhuxj201.util.UserHolder;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        //System.out.println("拦截成功"+req.getRequestURL());
        HttpSession session = req.getSession();
        Object user = session.getAttribute("user");
        if(user != null){
            //使用ThreadLocal为每个请求存储用户数据,以免并发线程时都从session获取用户数据而出错
            UserHolder.saveUser(user);
            return true;
        }
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest req, HttpServletResponse resp, Object handler, Exception ex) throws Exception {
        //当请求结束后,手动移除用户数据,避免内存溢出
        UserHolder.removeUser();
    }
}
